<!--
 * @Description: 订单页面
 * @Author: Gaq
 * @Date: 2022-11-06 21:49:48
 * @LastEditTime: 2023-02-20 19:28:23
 * @LastEditors: Gaq
-->
<script setup>
import request from "@/utils/request";
import { useStore } from "vuex";
import router from "@/router";
import { ElMessage } from "element-plus";

const { state, commit, dispatch } = useStore();
let addressList = computed(() => state.addressList);
let orderDetail = ref([]);
let isClicked = computed(() => state.isClicked);
let clicked = ref(isClicked);
let dialogShow = computed(() => state.dialogShow);
let dialogFormVisible = ref(dialogShow.value);

onBeforeMount(() => {
  JSON.parse(decodeURIComponent(localStorage.getItem("orderDetail"))) instanceof
  Array
    ? JSON.parse(decodeURIComponent(localStorage.getItem("orderDetail"))).map(
        (item) => {
          orderDetail.value.push(item);
        }
      )
    : orderDetail.value.push(
        JSON.parse(decodeURIComponent(localStorage.getItem("orderDetail")))
      );
  handleSum();
  dispatch("updateAddressList", state.userId);
});

const showIndex = (value) => {
  orderItem.addressId = value;
};
// 向表单组件传递地址 id 实现自动填充
let itemId = ref();
const clickItem = (value) => {
  itemId.value = value;
};
const showClick = (value) => {
  commit("SET_CLICKED", value);
};
const changeDialogState = () => {
  commit("SET_DIALOG", false);
};

const showDialog = () => {
  dialogFormVisible.value = true;
  commit("SET_DIALOG", true);
};
let sumPrice = ref(0);
const handleSum = () => {
  orderDetail.value.map((item) => {
    sumPrice.value += item.price * item.num;
  });
};

let orderItem = {};
const { proxy } = getCurrentInstance();
let flag = ref(1); //标识用户是否支付成功
let styleStock; //样式库存
const createOrder = () => {
  if(!addressList.value){
    ElMessage.error("请先添加地址~")
  } else{
    orderDetail.value.map((item) => {
    const { userId, goodsId, styleId, num, price, styleName, image } = item;
    orderItem = {
      userId,
      goodsId,
      styleId,
      num: num,
      price,
      addressId: 0,
      state: "已支付",
      styleName,
      image,
      payTime: proxy.$formDate(Date()),
      name: item.name,
      pay: sumPrice.value,
    };
    // console.log(styleId);
    orderItem.addressId = addressList.value[isClicked.value].addressId;
   request.post("/order/insertOne", orderItem).then((res) => {
      res.code == 0 ? (flag.value = 1) : (flag.value = 0);
    });
    request.get(`/style/getOne/${styleId}`).then((res) => {
      res.code == 0
        ? ((styleStock = res.data.styleStock - num),
          request
            .put(`/style/updateOne`, { styleId, styleStock })
            .then((res) => {
              if (res.code == -1) {
                console.log(res);
              }
            }))
        : console.log(res);
    }); 
  flag.value == 1 ? ElMessage.success("支付成功") : ElMessage.error("支付失败");
  });
  }
  
};
</script>

<template>
  <el-card class="box-card">
    <el-alert title="确认收货地址" type="success" :closable="false" />
    <!-- <span>确认收货地址</span> -->
    <el-empty description="地址为空" :image-size="100" v-if="!addressList"/>
    <div
      class="addressInfo"
      v-for="(item, index) in addressList"
      :class="index == clicked ? 'styleDefault' : ''"
    >
      <span>
        <el-radio-group @change="showClick(index)" :model-value="clicked">
          <el-radio
            :label="index"
            size="large"
            @change="showIndex(item.addressId)"
          >
            <span style="color: black"
              >{{ item.region }}/{{ item.detail }}&nbsp;&nbsp; ({{
                item.name
              }}&nbsp; 收)&nbsp;&nbsp; {{ item.phoneNumber }}</span
            >
          </el-radio>
        </el-radio-group>
      </span>
      <el-button
        text
        v-show="index == isClicked"
        class="updateAddress"
        @click.native="showDialog(), clickItem(item.addressId)"
        >修改本地址</el-button
      >
    </div>

    <el-alert title="确认订单信息" type="success" :closable="false" />
    <!-- <span>确认订单信息</span> -->
    <div class="orderList" v-for="order in orderDetail">
      <img :src="order.image" alt="加载失败" />
      <div class="infoBox">
        <p :title="order.name">
          {{ order.name }}
        </p>
        <p class="price">￥{{ (order.price * order.num).toFixed(2) }}</p>
        <p style="margin-top: 10px; font-size: smaller; color: #6c6c6c">
          样式名称：{{ order.styleName }}
        </p>
        <p style="position: absolute; right: 10px; bottom: 20px">
          ×{{ order.num }}
        </p>
      </div>
    </div>
    <div class="footer">
      实付款：<span style="font-size: x-large; color: red"
        >￥{{ sumPrice.toFixed(2) }}</span
      >
      <button :style="{'background-color': addressList ? 'rgb(242,45,0)':'rgba(242,45,0,0.5)'}" @click="createOrder" >
        立即支付
      </button>
    </div>
  </el-card>
  <el-dialog
    v-model="dialogFormVisible"
    @close="changeDialogState"
    v-if="dialogFormVisible"
  >
    <AddressForm :itemId="itemId"></AddressForm>
  </el-dialog>
</template>

<style lang="less" scoped>
.box-card {
  width: 70%;
  margin: 0 auto;
}
.addressInfo {
  margin-bottom: 5px;
  position: relative;
  cursor: pointer;
  &:hover {
    background-color: rgb(255, 240, 232);
  }
}
.orderList {
  margin-top: 10px;
  height: 120px;
  display: flex;
  position: relative;
  img {
    width: 120px;
    height: 120px;
  }
  .infoBox {
    margin-left: 10px;
    width: 410px;
    p {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
.styleDefault {
  background-color: rgb(255, 240, 232);
}
.updateAddress {
  color: rgb(94, 160, 219);
  font-size: x-small;
  position: absolute;
  right: 0px;
  top: 10%;
  &:hover {
    color: red;
  }
}
.el-button.is-text:focus,
.el-button.is-text:hover {
  background-color: transparent;
}
.price {
  position: absolute;
  right: 0px;
  font-size: large;
  color: red;
}
.footer {
  float: right;
  height: 30px;
  line-height: 30px;
  margin-top: 200px;
  padding-bottom: 20px;
  button {
    margin-left: 20px;
    float: right;
    cursor: pointer;
    border: none;
    color: white;
    border-radius: 5%;
    outline: none;
    width: 130px;
    height: 30px;
  }
}
</style>